/* $Id:stat.cc $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "stat"

#include <sstream>
#include <fstream>
#include "../general/util.h"
#include "../general/log.h"
#include "../general/channel.h"
#include "stat.h"
#include "../general/general.h"

stat::stat() {
    name="";
    type=-1;
    description="";
}

// Field : name

const string stat::getName() const { return name; }
void stat::setName(const string v) { name=v; }

// Field : type

const string statType[]={"item","person","unit","all"};
const int stat::getType() const { return type; }
const string stat::showType() const {
    if (type<0) return "";
    else return statType[type];
}
void stat::setType(const int  v) {
    if (v<0 || (unsigned int)v >= sizeof statType/sizeof statType[0]) type=-1;
    else type=v;
}
void stat::setType(const string v) {
    type=-1;
    loopArray(statType, tp, string) {
        if (v==*tp) {type=tp_i; break; }
    }
    if (type==-1) dbg_state("Enumerate stat.type %s has unknown '%s'", getName().c_str(), v.c_str());
}

// Field : description

const string stat::getDescription() const { return description; }
void stat::setDescription(const string v) { description=v; }

void stat::save(class channel &ch) {
    ch.write("stat", "");
    ch.write("n", getName());
    ch.write("t", getType());
    ch.write("d", getDescription());
}

void stat::load(class channel &ch) {
    if (ch.key=="n" || ch.key=="name") { setName(ch.value); ch.next(); }
    if (ch.key=="t" || ch.key=="type") { setType(ch.value); ch.next(); }
    if (ch.key=="d" || ch.key=="description") { setDescription(ch.value); ch.next(); }
}

void stat::xml(ofstream &f, int l, int r) {
    f << ncpy(l, "  ") << "<stat name=\"" << xml_encode(getName()) <<
    "\" type=\"" << showType() <<
    "\" description=\"" << xml_encode(getDescription()) <<
    "\"/>" << endl;
}

// Repository

statRepository stat_repo;

class stat& statRepository::getStat(const string v) { return stats[v]; }
void statRepository::setStat(class stat& v) {
    if (v.getName()=="") throw unnamed();
    stats[v.getName()]=v;
}
map<string,class stat>& statRepository::listStat() { return stats; }
void statRepository::delStat(const string v) { stats.erase(v); }
const bool statRepository::isStat(const string v) const { return stats.count(v)>0; }
void statRepository::save(class channel &ch) {
    loopStats(rec) {
        rec->save(ch);
    }
}

bool statRepository::load(class channel &ch) {
    if (ch.key=="stat") {
        ch.next();
        class stat rec;
        rec.load(ch);
        setStat(rec);
        return true;
    }
    return false;
}
